﻿using justice.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace justice.Controllers
{
    public class decideAttribute : FilterAttribute, IAuthorizationFilter
    {
        public bool IsCheck { get; set; }
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            justiceEntities dal = new justiceEntities();
            if (IsCheck)
            {
                if (filterContext.HttpContext.Session["uid"] == null)
                {
                    filterContext.HttpContext.Response.Redirect("/Admin/LoginIndex");
                }
                else
                {
                    var controllerName = (filterContext.RouteData.Values["controller"]).ToString().ToLower();
                    var actionName = (filterContext.RouteData.Values["action"]).ToString().ToLower();
                    //var areaName = (filterContext.RouteData.DataTokens["area"] == null ? "" : filterContext.RouteData.DataTokens["area"]).ToString().ToLower();
                    string modernPath = "/" + controllerName + "/" + actionName;
                    justice_user user = dal.justice_user.ToList().Find(l => l.id == Convert.ToInt32(filterContext.HttpContext.Session["uid"]));
                    Role role = dal.Role.ToList().Find(l => l.id == user.role_id);
                    string[] authids = role.auths.Split(',');
                    List<string> authpath = new List<string>();
                    foreach (var item in authids)
                    {
                        auth au = dal.auth.ToList().Find(l => l.auth_id == Convert.ToInt32(item));
                        authpath.Add(au.auth_path);
                    }
                    bool s = false;
                    foreach (var item in authpath)
                    {
                        if (item.ToLower() == modernPath)
                        {
                            s = true;
                            break;
                        }
                    }


                    if (!s)
                    {
                        //string html = "<h1 style='text-align:center;margin-top:100px;'>你无权访问本页面，<a href='javascript: history.go(-1);'>点击返回</a></h1>";
                        //filterContext.HttpContext.Response.Write(html);
                        //filterContext.HttpContext.Response.Redirect("/Home/error");
                        //filterContext.Result = new ContentResult();
                        filterContext.Result = new RedirectResult("/Home/error");
                    }
                }
            }
        }

    }
}